const getWxLocation = () => {
    wx.showLoading({
        title: '正在获取数据...',
        mask: true,
    })
    return new Promise((resolve, reject) => {
        let _locationChangeFn = (res) => {
            console.log('location change', res)
            resolve(res)
            wx.hideLoading()
            wx.offLocationChange(_locationChangeFn)
        }
        wx.startLocationUpdate({
            type: 'gcj02',
            //type: 'wgs84',
            success: (res) => {
                wx.onLocationChange(_locationChangeFn)
            },
            fail: (err) => {
                console.log('获取当前位置失败', err)
                wx.hideLoading()
                reject()
            }
        })
    })
}

const toSetting = () => {
    return new Promise((resolve, reject) => {
        wx.openSetting({
            async success(res) {
                console.log(res)
                if (res.authSetting["scope.userLocation"]) {
                    // res.authSetting["scope.userLocation"]为trueb表示用户已同意获得定位信息，此时调用getlocation可以拿到信息
                    let locationRes = await getWxLocation()
                    resolve(locationRes)
                }
            },
            fail(err) {
                reject()
            }
        })
    })
}

const authorization = async () => {
    try {
        return await getWxLocation();
    } catch {
        wx.showModal({
            title: '温馨提示',
            content: '获取权限失败，需要获取您的地理位置才能为您提供更好的服务！是否授权获取地理位置？',
            success: function (res) {
                if (res.confirm) {
                    toSetting()
                } else {
                    console.log('用户点击取消')
                }
            }
        })
    }
}

module.exports = { getWxLocation, toSetting, authorization }